package editorRozpisu;

import generovanieRozpisu.SpustacGeneratora;
import generovanieRozpisu.ondrejovGenerator;
import importExportDat.ImportExportCSV;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.File;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import strukturaRozpis.Rozpis;
import strukturaZamestnanciNepritomnost.Zamestnanci;
import strukturaZamestnanciNepritomnost.Zamestnanec;

/**
 *
 * @author Dominik
 */
public class ZobrazRozpis extends javax.swing.JFrame {

    private int mesiac, rok;
    private Rozpis roz;
    private Rozpis minRoz; //minuly rozpis - mesiac dozadu
    private Rozpis budRoz; //buduci rozpis - mesiac dopredu
    private Zamestnanci zam;
    private DefaultTableModel myTabel;
    private JComboBox comboBox;
    private String headers[] = new String[9];
    private int zobrazene = 0;  // -1=minRoz, 0=roz, 1=budRoz
    final String[] MONTHS = {"januar", "februar", "marec", "april", "maj", "jun", "jul", "august", "september", "oktober", "november", "december"};
    private final String[] nazvyMesiacov = {"Január", "Február", "Marec", "Apríl", "Máj", "Jún",
        "Júl", "August", "September", "Október", "November", "December"}; //indexovane od 0-11

    /**
     * Creates new form ZobrazRozpis
     */
    public ZobrazRozpis(int mesiacNew, int rokNew) {
        initComponents();

        mesiac = mesiacNew;
        rok = rokNew;
        //centralizovanie okna
        Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
        int X = (screen.width / 2) - (this.getWidth() / 2); // Center horizontally.
        int Y = (screen.height / 2) - (this.getHeight() / 2); // Center vertically.
        this.setLocation(X, Y);

        // nacitanie rozpisu na aktualny mesiac
        try {
            //nacitanie aktualneho rozpisu
            roz = new SpustacGeneratora(mesiac, rok).getRozpis();
            //nacitanie minuleho rozpisu
            // KOMENT
            if (mesiac == 1) {  //ak je januar(0) + 1, tak minuly je december(11) + 1
                minRoz = new SpustacGeneratora(12, rok - 1).getRozpis();
            } else {
                minRoz = new SpustacGeneratora(mesiac - 1, rok).getRozpis();
            }
            //nacitanie buduceho rozpisu
            if (mesiac == 12) {
                budRoz = new SpustacGeneratora(1, rok + 1).getRozpis();
            } else {
                budRoz = new SpustacGeneratora(mesiac + 1, rok).getRozpis();
            }
            // KOMENT
        } catch (SQLException ex) {
            Logger.getLogger(Rozpis.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            Logger.getLogger(Rozpis.class.getName()).log(Level.SEVERE, null, ex);
        }
        // nacitanie zamestnancov
        try {
            zam = new Zamestnanci();
        } catch (SQLException ex) {
            Logger.getLogger(Zamestnanci.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            Logger.getLogger(Zamestnanci.class.getName()).log(Level.SEVERE, null, ex);
        }
        // vytvorenie podkladu zakladneho modelu tabulky, vytvaranie stlpcov tabulky
        myTabel = new DefaultTableModel();

        headers[0] = "Deň";
        headers[1] = "F_denná 1";
        headers[2] = "F_denná 2";
        headers[3] = "M_denná 1";
        headers[4] = "M_denná 2";
        headers[5] = "F_nočná 1";
        headers[6] = "F_nočná 2";
        headers[7] = "M_nočná 1";
        headers[8] = "M_nočná 2";
        myTabel.setColumnIdentifiers(headers);

        ZobrazRozpisTable.setModel(myTabel);
        TableColumn columnDen = ZobrazRozpisTable.getTableHeader().getColumnModel().getColumn(0);
        columnDen.setMaxWidth(40);

        // zadefinovanie jednotlivych stlpcov tabulky vypisu rozpisu
        TableColumn F_denna1 = ZobrazRozpisTable.getColumnModel().getColumn(1);
        F_denna1.setCellRenderer(new RendererTypZamestnanca());
        TableColumn F_denna2 = ZobrazRozpisTable.getColumnModel().getColumn(2);
        F_denna2.setCellRenderer(new RendererTypZamestnanca());
        TableColumn M_denna1 = ZobrazRozpisTable.getColumnModel().getColumn(3);
        M_denna1.setCellRenderer(new RendererTypZamestnanca());
        TableColumn M_denna2 = ZobrazRozpisTable.getColumnModel().getColumn(4);
        M_denna2.setCellRenderer(new RendererTypZamestnanca());
        TableColumn F_nocna1 = ZobrazRozpisTable.getColumnModel().getColumn(5);
        F_nocna1.setCellRenderer(new RendererTypZamestnanca());
        TableColumn F_nocna2 = ZobrazRozpisTable.getColumnModel().getColumn(6);
        F_nocna2.setCellRenderer(new RendererTypZamestnanca());
        TableColumn M_nocna1 = ZobrazRozpisTable.getColumnModel().getColumn(7);
        M_nocna1.setCellRenderer(new RendererTypZamestnanca());
        TableColumn M_nocna2 = ZobrazRozpisTable.getColumnModel().getColumn(8);
        M_nocna2.setCellRenderer(new RendererTypZamestnanca());

        comboBox = new JComboBox();
        // doplnenie po maximalny pocet zamestnancov (moznosti v ComboBoxe)
        if (zam.isConnected()) {
            int j = 0;
            for (int i : zam.getZamestnanciActive().keySet()) {
                comboBox.addItem(zam.getZamestnanec(i).getPriezvisko() + " " + zam.getZamestnanec(i).getMeno());
                //comboBox.getItemAt(i);
                j++;
            }
            comboBox.addItem("-");
        }
        // pridanie ComboBoxov do jednotlivych policok tabulky, resp. celych stlpcov
        F_denna1.setCellEditor(new DefaultCellEditor(comboBox));
        F_denna2.setCellEditor(new DefaultCellEditor(comboBox));
        M_denna1.setCellEditor(new DefaultCellEditor(comboBox));
        M_denna2.setCellEditor(new DefaultCellEditor(comboBox));
        F_nocna1.setCellEditor(new DefaultCellEditor(comboBox));
        F_nocna2.setCellEditor(new DefaultCellEditor(comboBox));
        M_nocna1.setCellEditor(new DefaultCellEditor(comboBox));
        M_nocna2.setCellEditor(new DefaultCellEditor(comboBox));

        // vypisanie vsetkych smien
        if (roz.isConnected()) {
            vypisDni(roz);
            vypisSmeny(roz);
        } else {
            System.out.println("Nefunkcny rozpis!");
        }
        jButton3.setBackground(Color.white);
        jButton4.setBackground(Color.yellow);
        jButton5.setBackground(Color.white);
        jLabel1.setText(nazvyMesiacov[mesiac - 1] + " " + rok);
        setTitle(nazvyMesiacov[mesiac - 1] + " " + rok);
    }

    private void refresh() {
        initComponents();

        //centralizovanie okna
        Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
        int X = (screen.width / 2) - (this.getWidth() / 2); // Center horizontally.
        int Y = (screen.height / 2) - (this.getHeight() / 2); // Center vertically.
        this.setLocation(X, Y);

        // nacitanie rozpisu na aktualny mesiac
        try {
            //nacitanie aktualneho rozpisu
            roz = new SpustacGeneratora(mesiac, rok).getRozpis();
            //nacitanie minuleho rozpisu
            // KOMENT
            if (mesiac == 1) {  //ak je januar(0) + 1, tak minuly je december(11) + 1
                minRoz = new SpustacGeneratora(12, rok - 1).getRozpis();
            } else {
                minRoz = new SpustacGeneratora(mesiac - 1, rok).getRozpis();
            }
            //nacitanie buduceho rozpisu
            if (mesiac == 12) {
                budRoz = new SpustacGeneratora(1, rok + 1).getRozpis();
            } else {
                budRoz = new SpustacGeneratora(mesiac + 1, rok).getRozpis();
            }
            // KOMENT
        } catch (SQLException ex) {
            Logger.getLogger(Rozpis.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            Logger.getLogger(Rozpis.class.getName()).log(Level.SEVERE, null, ex);
        }
        // nacitanie zamestnancov
        try {
            zam = new Zamestnanci();
        } catch (SQLException ex) {
            Logger.getLogger(Zamestnanci.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            Logger.getLogger(Zamestnanci.class.getName()).log(Level.SEVERE, null, ex);
        }
        // vytvorenie podkladu zakladneho modelu tabulky, vytvaranie stlpcov tabulky
        myTabel = new DefaultTableModel();

        headers[0] = "Deň";
        headers[1] = "F_denná 1";
        headers[2] = "F_denná 2";
        headers[3] = "M_denná 1";
        headers[4] = "M_denná 2";
        headers[5] = "F_nočná 1";
        headers[6] = "F_nočná 2";
        headers[7] = "M_nočná 1";
        headers[8] = "M_nočná 2";
        myTabel.setColumnIdentifiers(headers);

        ZobrazRozpisTable.setModel(myTabel);
        TableColumn columnDen = ZobrazRozpisTable.getTableHeader().getColumnModel().getColumn(0);
        columnDen.setMaxWidth(40);

        // zadefinovanie jednotlivych stlpcov tabulky vypisu rozpisu
        TableColumn F_denna1 = ZobrazRozpisTable.getColumnModel().getColumn(1);
        F_denna1.setCellRenderer(new RendererTypZamestnanca());
        TableColumn F_denna2 = ZobrazRozpisTable.getColumnModel().getColumn(2);
        F_denna2.setCellRenderer(new RendererTypZamestnanca());
        TableColumn M_denna1 = ZobrazRozpisTable.getColumnModel().getColumn(3);
        M_denna1.setCellRenderer(new RendererTypZamestnanca());
        TableColumn M_denna2 = ZobrazRozpisTable.getColumnModel().getColumn(4);
        M_denna2.setCellRenderer(new RendererTypZamestnanca());
        TableColumn F_nocna1 = ZobrazRozpisTable.getColumnModel().getColumn(5);
        F_nocna1.setCellRenderer(new RendererTypZamestnanca());
        TableColumn F_nocna2 = ZobrazRozpisTable.getColumnModel().getColumn(6);
        F_nocna2.setCellRenderer(new RendererTypZamestnanca());
        TableColumn M_nocna1 = ZobrazRozpisTable.getColumnModel().getColumn(7);
        M_nocna1.setCellRenderer(new RendererTypZamestnanca());
        TableColumn M_nocna2 = ZobrazRozpisTable.getColumnModel().getColumn(8);
        M_nocna2.setCellRenderer(new RendererTypZamestnanca());

        comboBox = new JComboBox();
        // doplnenie po maximalny pocet zamestnancov (moznosti v ComboBoxe)
        if (zam.isConnected()) {
            int j = 0;
            for (int i : zam.getZamestnanciActive().keySet()) {
                comboBox.addItem(zam.getZamestnanec(i).getPriezvisko() + " " + zam.getZamestnanec(i).getMeno());
                //comboBox.getItemAt(i);
                j++;
            }
        }
        // pridanie ComboBoxov do jednotlivych policok tabulky, resp. celych stlpcov
        F_denna1.setCellEditor(new DefaultCellEditor(comboBox));
        F_denna2.setCellEditor(new DefaultCellEditor(comboBox));
        M_denna1.setCellEditor(new DefaultCellEditor(comboBox));
        M_denna2.setCellEditor(new DefaultCellEditor(comboBox));
        F_nocna1.setCellEditor(new DefaultCellEditor(comboBox));
        F_nocna2.setCellEditor(new DefaultCellEditor(comboBox));
        M_nocna1.setCellEditor(new DefaultCellEditor(comboBox));
        M_nocna2.setCellEditor(new DefaultCellEditor(comboBox));

        // vypisanie vsetkych smien
        if (roz.isConnected()) {
            vypisDni(roz);
            vypisSmeny(roz);
        } else {
            System.out.println("Nefunkcny rozpis!");
        }
        setTitle(nazvyMesiacov[mesiac - 1] + " " + rok);
    }

    private boolean vypisDni(Rozpis r) {
        int j = 1;
        for (int i = 0; i < (r.getNumberOfDays()); i++) {
            myTabel.addRow(headers);
            myTabel.setValueAt(j, i, 0);
            j++;
        }
        return true;
    }

    private boolean vypisSmeny(Rozpis r) {  // r = minRoz/roz/budRoz
        int zam1;
        int zam2;
        int k;
        if (r.getRozpis() == null) {
            System.out.println("Nie je vytvoreny este rozpis!");
            vymazRiadkyTab();
            return false;
        }

        // vypis zvolenych zamestnancov na smeny, podla vygenerovaneho rozpisu
        for (int i = 1; i <= r.getNumberOfDays(); i++) {  //idem cez vsetky dni mesiaca            
            k = 1;
            for (int j = 0; j <= 3; j++) {       //idem cez vsetky sluzby dna
                zam1 = r.getRozpis().get(i).get(j).getID_zam1(); //vrati ID zamestnanca1, ktory ma 1.sluzbu
                zam2 = r.getRozpis().get(i).get(j).getID_zam2(); //vrati ID zamestnanca2, ktory ma 1.sluzbu(s nim)
                //if (zam1 != 0) {
                ZobrazRozpisTable.setValueAt(vratMeno(zam1), i - 1, k++);  //valueAt(na aky string, row, column)
                //}
                //if (zam2 != 0) {
                ZobrazRozpisTable.setValueAt(vratMeno(zam2), i - 1, k++);  //valueAt(na aky string, row, column)
                //}
            }
        }
        return true;
    }

    private boolean vymazRiadkyTab() {
        myTabel.getDataVector().removeAllElements();
        comboBox.setEditable(false);
        return true;
    }

    private String kontrolaDna(Rozpis r, int kontrolovanyDen) {
        Set smenari = new HashSet();
        JComboBox comb;
        for (int i = 1; i <= (ZobrazRozpisTable.getColumnCount() - 1); i++) {
            if (smenari.contains(vratIDzamestnanca(ZobrazRozpisTable.getValueAt(kontrolovanyDen, i).toString()))) {
//                  comb = (JComboBox)
//                   ZobrazRozpisTable.getCellEditor().getTableCellEditorComponent(ZobrazRozpisTable, null, rootPaneCheckingEnabled, kontrolovanyDen, i);
//                   comb = ZobrazRozpisTable.getValueAt(kontrolovanyDen, i);
                // ZobrazRozpisTable.getCellEditor().getTableCellEditorComponent(ZobrazRozpisTable, comboBox, rootPaneCheckingEnabled, kontrolovanyDen, i);
                //  comb.setBackground(Color.red);
                // ZobrazRozpisTable.getCellEditor().
                return ZobrazRozpisTable.getValueAt(kontrolovanyDen, i).toString();
            } else {
                smenari.add(vratIDzamestnanca(ZobrazRozpisTable.getValueAt(kontrolovanyDen, i).toString()));
            }
        }
        return "";
    }

    private String kontrolaSluzbyNextDay(Rozpis r, int kontrolovanyDen) {
        Set smenariNoc = new HashSet();
        for (int i = 5; i <= 8; i++) {
            smenariNoc.add(vratIDzamestnanca(ZobrazRozpisTable.getValueAt(kontrolovanyDen, i).toString())); //v mnozine smenariNoc - nocna sluzba v kontrDen
        }
        if (kontrolovanyDen != (r.getNumberOfDays() - 1)) {
            for (int j = 1; j <= 4; j++) {
                if (smenariNoc.contains(vratIDzamestnanca(ZobrazRozpisTable.getValueAt(kontrolovanyDen + 1, j).toString()))) {
                    return ZobrazRozpisTable.getValueAt(kontrolovanyDen + 1, j).toString();
                }
            }
        }
        return "";
    }

    private String kontrolaTypuZamestnanca(Rozpis r, int kontrolovanyDen) {
        for (int i = 5; i <= 8; i++) {
            if (zam.getZamestnanec(vratIDzamestnanca(ZobrazRozpisTable.getValueAt(kontrolovanyDen, i).toString())).getTypZamestnanca() == 0) {
                return ZobrazRozpisTable.getValueAt(kontrolovanyDen, i).toString();
            }
        }
        return "";
    }

    private boolean ulozZmeny(Rozpis r) {
        for (int i = 0; i <= (r.getNumberOfDays() - 1); i++) {   // rows - dni mesiaca (v tabulke od 0 - 29, preto "-1")
            for (int j = 1; j <= ZobrazRozpisTable.getColumnCount(); j++) {   // columns - jednotlive smeny - stlpcov 8 [0..7]; 0-dni, 1..7-smeny
                switch (j) {
                    case 1: {
                        try {
                            r.setZamestnanec1(i + 1, 0, vratIDzamestnanca(ZobrazRozpisTable.getValueAt(i, j).toString()));
                        } catch (SQLException ex) {
                            Logger.getLogger(ZobrazRozpis.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        break;
                    }
                    case 2: {
                        try {
                            r.setZamestnanec2(i + 1, 0, vratIDzamestnanca(ZobrazRozpisTable.getValueAt(i, j).toString()));
                        } catch (SQLException ex) {
                            Logger.getLogger(ZobrazRozpis.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        break;
                    }
                    case 3: {
                        try {
                            r.setZamestnanec1(i + 1, 1, vratIDzamestnanca(ZobrazRozpisTable.getValueAt(i, j).toString()));
                        } catch (SQLException ex) {
                            Logger.getLogger(ZobrazRozpis.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        break;
                    }
                    case 4: {
                        try {
                            r.setZamestnanec2(i + 1, 1, vratIDzamestnanca(ZobrazRozpisTable.getValueAt(i, j).toString()));
                        } catch (SQLException ex) {
                            Logger.getLogger(ZobrazRozpis.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        break;
                    }
                    case 5: {
                        try {
                            r.setZamestnanec1(i + 1, 2, vratIDzamestnanca(ZobrazRozpisTable.getValueAt(i, j).toString()));
                        } catch (SQLException ex) {
                            Logger.getLogger(ZobrazRozpis.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        break;
                    }
                    case 6: {
                        try {
                            r.setZamestnanec2(i + 1, 2, vratIDzamestnanca(ZobrazRozpisTable.getValueAt(i, j).toString()));
                        } catch (SQLException ex) {
                            Logger.getLogger(ZobrazRozpis.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        break;
                    }
                    case 7: {
                        try {
                            r.setZamestnanec1(i + 1, 3, vratIDzamestnanca(ZobrazRozpisTable.getValueAt(i, j).toString()));
                        } catch (SQLException ex) {
                            Logger.getLogger(ZobrazRozpis.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        break;
                    }
                    case 8: {
                        try {
                            r.setZamestnanec2(i + 1, 3, vratIDzamestnanca(ZobrazRozpisTable.getValueAt(i, j).toString()));
                        } catch (SQLException ex) {
                            Logger.getLogger(ZobrazRozpis.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        break;
                    }
                    default: {
                        break;
                    }
                } // koniec switchu
            } // koniec j cyklu
        } // koniec i cyklu     
        return true;
    }

    private String vratMeno(int idZam) {
        // metoda, ktora vraci meno podla ID zamestnanca, v tvare "Priezvisko Meno"
        String result = "-";
        if (idZam != 0) {
            result = /*zam.getZamestnanci().get(idZam).getTypZamestnanca() + " " + */ zam.getZamestnanciAll().get(idZam).getPriezvisko() + " " + zam.getZamestnanciAll().get(idZam).getMeno();
        }
        return result;
    }

    private int vratIDzamestnanca(String priezmeno) {
        if (!priezmeno.equals("-")) {
            String priezvisko = priezmeno.substring(0, priezmeno.indexOf(" "));
            String meno = priezmeno.substring(priezmeno.indexOf(" ") + 1);
            for (Map.Entry<Integer, Zamestnanec> elem : zam.getZamestnanciAll().entrySet()) {
                int id = elem.getKey();
                Zamestnanec zamPom = elem.getValue();
                if (zamPom.getMeno().equals(meno) && zamPom.getPriezvisko().equals(priezvisko)) {
                    return id;
                }
            }
        }
        return 0;
    }

    private void ulozRozpisDoPdf(Rozpis rozp) {

        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new File(System.getProperty("user.home")));
        chooser.setSelectedFile(new File("rozpis_" + MONTHS[rozp.getMonth() - 1] + "_" + rozp.getYear() + ".pdf"));
        chooser.setFileFilter(new FileFilter() {
            @Override
            public boolean accept(File f) {
                return f.getName().toLowerCase().endsWith(".pdf") || f.isDirectory();
            }

            @Override
            public String getDescription() {
                return "PDF Files";
            }
        });
        int r = chooser.showSaveDialog(this);
        if (r == JFileChooser.APPROVE_OPTION) {
            String pdfname = chooser.getSelectedFile().getPath();
            if (!pdfname.endsWith(".pdf")) {
                pdfname += ".pdf";
            }
            // ak existuje uz taky file, upozorni uzivatela
            boolean exists = (new File(pdfname)).exists();
            if (exists) {
                int volba = JOptionPane.showConfirmDialog(this, "Rovnaký súbor už existuje, prajete si ho prepísať?.", "Info", JOptionPane.YES_NO_OPTION);
                if (volba == JOptionPane.NO_OPTION) {
                    return;
                }
            }
            CreatePDF cpdf = new CreatePDF(rozp, zam);
            boolean uloz = cpdf.savePDF(pdfname);
            if (!uloz) {
                JOptionPane.showMessageDialog(this, "Nepodarilo sa uložiť rozpis.", "Chyba", JOptionPane.ERROR_MESSAGE);
            }
        }

        //ulozenie, upload a zmazanie suboru
        CreatePDF cpdf = new CreatePDF(rozp, zam);
        String fileName = rozp.getYear() + "_" + String.format("%02d", rozp.getMonth()) + ".pdf";
        if (!cpdf.savePDF(fileName)) {
            JOptionPane.showMessageDialog(this, "Nepodarilo sa vytvorit rozpis v PDF.", "Chyba", JOptionPane.ERROR_MESSAGE);
        } else {
            if (!CreatePDF.uploadFile(fileName)) {
                JOptionPane.showMessageDialog(this, "Nepodarilo sa uploadnut PDF.", "Chyba", JOptionPane.ERROR_MESSAGE);
            } else {
                File f1 = new File(fileName);
                if (!f1.delete()) {
                    JOptionPane.showMessageDialog(this, "Nepodarilo sa zmazat PDF po uploadnuti na server.", "Chyba", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        ZobrazRozpisTable = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jButton7 = new javax.swing.JButton();
        jButton8 = new javax.swing.JButton();
        jButton9 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        ZobrazRozpisTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(ZobrazRozpisTable);

        jButton1.setText("Potvrdiť zmeny");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Zrušiť");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Minulý mesiac");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jLabel1.setText("jLabel1");

        jButton4.setText("Aktuálny mesiac");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton5.setText("Budúci mesiac");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        jButton6.setText("Import");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                importRozpis(evt);
            }
        });

        jButton7.setText("Export");
        jButton7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                export(evt);
            }
        });

        jButton8.setText("Hodiny");
        jButton8.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton8ActionPerformed(evt);
            }
        });

        jButton9.setText("Generuj");
        jButton9.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton9ActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 1002, Short.MAX_VALUE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jButton2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .add(layout.createSequentialGroup()
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(jButton7)
                                    .add(jButton1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 147, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                                        .add(org.jdesktop.layout.GroupLayout.LEADING, jButton8, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .add(org.jdesktop.layout.GroupLayout.LEADING, jButton6, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                    .add(jButton9))
                                .add(0, 0, Short.MAX_VALUE))))
                    .add(layout.createSequentialGroup()
                        .add(jButton3)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(jButton4)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(jButton5)
                        .add(112, 112, 112)
                        .add(jLabel1)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(20, 20, 20)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jButton3)
                    .add(jLabel1)
                    .add(jButton4)
                    .add(jButton5))
                .add(1, 1, 1)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(jButton1)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jButton2)
                        .add(106, 106, 106)
                        .add(jButton9)
                        .add(85, 85, 85)
                        .add(jButton8)
                        .add(160, 160, 160)
                        .add(jButton6)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(jButton7)
                        .add(17, 17, 17))
                    .add(jScrollPane1)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here: 
        try {
            if (zobrazene == -1) {
                if (kontrolaRozpisu(minRoz)) {
                    ulozZmeny(minRoz);
                    minRoz.commitSluzby();
                    ulozRozpisDoPdf(minRoz);
                    vymazRiadkyTab();
                    this.dispose();
                }
            } else if (zobrazene == 0) {
                if (kontrolaRozpisu(roz)) {
                    ulozZmeny(roz);
                    roz.commitSluzby();
                    ulozRozpisDoPdf(roz);
                    vymazRiadkyTab();
                    this.dispose();
                }
            } else if (zobrazene == 1) {
                if (kontrolaRozpisu(budRoz)) {
                    ulozZmeny(budRoz);
                    budRoz.commitSluzby();
                    ulozRozpisDoPdf(budRoz);
                    vymazRiadkyTab();
                    this.dispose();
                }
            } else {
                System.out.println("Chybny rozpis!");
            }
        } catch (SQLException ex) {
            Logger.getLogger(ZobrazRozpis.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            Logger.getLogger(ZobrazRozpis.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // tlacitko zobrazenia minRoz
        if (zobrazene == -1) {
            ulozZmeny(minRoz);
        } else if (zobrazene == 0) {
            ulozZmeny(roz);
        } else if (zobrazene == 1) {
            ulozZmeny(budRoz);
        }
        jButton3.setBackground(Color.yellow);
        jButton4.setBackground(Color.white);
        jButton5.setBackground(Color.white);
        vymazRiadkyTab();
        if (minRoz.isConnected()) {
            vypisDni(minRoz);
            vypisSmeny(minRoz);
        } else {
            System.out.println("Nefunkcny rozpis!");
        }
        zobrazene = -1;

        if (mesiac == 1) {
            jLabel1.setText(nazvyMesiacov[11] + " " + (rok - 1));
            setTitle(nazvyMesiacov[11] + " " + (rok - 1));
        } else {
            jLabel1.setText(nazvyMesiacov[mesiac - 2] + " " + rok);
            setTitle(nazvyMesiacov[mesiac - 2] + " " + rok);
        }
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        // tlacitko zobrazenia Roz
        if (zobrazene == -1) {
            ulozZmeny(minRoz);
        } else if (zobrazene == 0) {
            ulozZmeny(roz);
        } else if (zobrazene == 1) {
            ulozZmeny(budRoz);
        }
        jButton3.setBackground(Color.white);
        jButton4.setBackground(Color.yellow);
        jButton5.setBackground(Color.white);
        vymazRiadkyTab();
        if (roz.isConnected()) {
            vypisDni(roz);
            vypisSmeny(roz);
        } else {
            System.out.println("Nefunkcny rozpis!");
        }
        zobrazene = 0;

        jLabel1.setText(nazvyMesiacov[mesiac - 1] + " " + rok);
        setTitle(nazvyMesiacov[mesiac - 1] + " " + rok);
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        // tlacitko zobrazenia budRoz
        if (zobrazene == -1) {
            ulozZmeny(minRoz);
        } else if (zobrazene == 0) {
            ulozZmeny(roz);
        } else if (zobrazene == 1) {
            ulozZmeny(budRoz);
        }
        jButton3.setBackground(Color.white);
        jButton4.setBackground(Color.white);
        jButton5.setBackground(Color.yellow);
        vymazRiadkyTab();
//        if(budRoz.getRozpis() == null){
//            System.out.println("Nefunkcny rozpis! Pravdepodobne este nebol vytvoreny!");
//        }
        if (budRoz.isConnected()) {
            vypisDni(budRoz);
            vypisSmeny(budRoz);
        } else {
            System.out.println("Nefunkcny rozpis!");
        }
        zobrazene = 1;

        if (mesiac == 12) {
            jLabel1.setText(nazvyMesiacov[0] + " " + (rok + 1));
            setTitle(nazvyMesiacov[0] + " " + (rok + 1));
        } else {
            jLabel1.setText(nazvyMesiacov[mesiac] + " " + rok);
            setTitle(nazvyMesiacov[mesiac] + " " + rok);
        }
    }//GEN-LAST:event_jButton5ActionPerformed

    private void export(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_export
        // export rozpisu
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new File(System.getProperty("user.home")));

        // vyber spravny rozpis na export
        Rozpis tmp;
        if (zobrazene == -1) {
            tmp = minRoz;
        } else if (zobrazene == 0) {
            tmp = roz;
        } else {
            tmp = budRoz;
        }
        chooser.setSelectedFile(new File("rozpis_" + MONTHS[tmp.getMonth() - 1] + "_" + tmp.getYear() + ".csv"));
        chooser.setFileFilter(new FileFilter() {
            @Override
            public boolean accept(File f) {
                return f.getName().toLowerCase().endsWith(".csv") || f.isDirectory();
            }

            @Override
            public String getDescription() {
                return "CSV Files";
            }
        });
        int r = chooser.showSaveDialog(this);
        if (r == JFileChooser.APPROVE_OPTION) {
            String csvname = chooser.getSelectedFile().getPath();
            if (!csvname.endsWith(".csv")) {
                csvname += ".csv";
            }
            // ak existuje uz taky file, upozorni uzivatela
            boolean exists = (new File(csvname)).exists();
            if (exists) {
                int volba = JOptionPane.showConfirmDialog(this, "Rovnaký súbor už existuje, prajete si ho prepísať?.", "Info", JOptionPane.YES_NO_OPTION);
                if (volba == JOptionPane.NO_OPTION) {
                    return;
                }
            }
            ImportExportCSV importexport = new ImportExportCSV(this);
            boolean exportRozpis = importexport.exportRozpis(csvname, tmp, zam);
            if (!exportRozpis) {
                JOptionPane.showMessageDialog(this, "Nepodarilo sa exportovať rozpis.", "Chyba", JOptionPane.ERROR_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(this, "Rozpis bol ulozeny do zvoleneho suboru.", "Info", JOptionPane.INFORMATION_MESSAGE);
            }
        }
    }//GEN-LAST:event_export

    private void importRozpis(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_importRozpis
        // import rozpisu

        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new File(System.getProperty("user.home")));
        chooser.setSelectedFile(new File("subor_s_rozpisom.csv"));
        chooser.setFileFilter(new FileFilter() {
            @Override
            public boolean accept(File f) {
                return f.getName().toLowerCase().endsWith(".csv") || f.isDirectory();
            }

            @Override
            public String getDescription() {
                return "CSV Files";
            }
        });
        int r = chooser.showOpenDialog(this);
        if (r == JFileChooser.APPROVE_OPTION) {
            String csvname = chooser.getSelectedFile().getPath();
            ImportExportCSV importexport = new ImportExportCSV(this);
            boolean importRozpis = false;
            try {
                importRozpis = importexport.importRozpis(csvname, zam);
            } catch (SQLException | ParseException ex) {
                Logger.getLogger(ZobrazRozpis.class.getName()).log(Level.SEVERE, null, ex);
            }
            if (importRozpis == false) {
                JOptionPane.showMessageDialog(this, "Nepodarilo sa načítať rozpis !", "Chyba", JOptionPane.ERROR_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(this, "Nacital sa rozpis zo zvoleneho suboru.", "Info", JOptionPane.INFORMATION_MESSAGE);
                refresh();
            }
        }        // TODO add your handling code here:
    }//GEN-LAST:event_importRozpis

    private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
        Hodiny h = null;
        if (zobrazene == -1) {
            ulozZmeny(minRoz);
            h = new Hodiny(minRoz);
        } else if (zobrazene == 0) {
            ulozZmeny(roz);
            h = new Hodiny(roz);
        } else if (zobrazene == 1) {
            ulozZmeny(budRoz);
            h = new Hodiny(budRoz);
        }

        h.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        h.setVisible(true);
    }//GEN-LAST:event_jButton8ActionPerformed

    private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed
        try {
            Rozpis rozpisTemp = null;
            Rozpis lastMonth;
            int mesiacTemp;
            int rokTemp;
            if (mesiac == 1) {
                lastMonth = new Rozpis(12, rok - 1);
            } else {
                lastMonth = new Rozpis(mesiac - 1, rok);
            }
            if (zobrazene == -1) {
                if(mesiac==1){
                    mesiacTemp =12;
                    rokTemp = rok-1;
                }else{
                    mesiacTemp =mesiac-1;
                    rokTemp = rok;
                }
                ondrejovGenerator g = new ondrejovGenerator(mesiacTemp, rokTemp, lastMonth.getPoslednuSluzbuMinulehoMesiaca());
                minRoz = g.generuj();
                rozpisTemp = minRoz;
            } else if (zobrazene == 0) {
                ondrejovGenerator g = new ondrejovGenerator(mesiac, rok, lastMonth.getPoslednuSluzbuMinulehoMesiaca());
                roz = g.generuj();
                rozpisTemp = roz;
            } else if (zobrazene == 1) {
                if(mesiac==12){
                    mesiacTemp =1;
                    rokTemp = rok+1;
                }else{
                    mesiacTemp =mesiac+1;
                    rokTemp = rok;
                }
                ondrejovGenerator g = new ondrejovGenerator(mesiacTemp, rokTemp, lastMonth.getPoslednuSluzbuMinulehoMesiaca());
                budRoz = g.generuj();
                rozpisTemp = budRoz;
            }

            vymazRiadkyTab();
            if (rozpisTemp.isConnected()) {
                vypisDni(rozpisTemp);
                vypisSmeny(rozpisTemp);
            } else {
                System.out.println("Nefunkcny rozpis!");
            }

        } catch (Exception e) {
        }
    }//GEN-LAST:event_jButton9ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new ZobrazRozpis(12, 2012).setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable ZobrazRozpisTable;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JButton jButton7;
    private javax.swing.JButton jButton8;
    private javax.swing.JButton jButton9;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables

    private boolean kontrolaRozpisu(Rozpis r) {
        for (int i = 0; i <= (r.getNumberOfDays() - 1); i++) { //cez vsetky dni mesiaca
            if (!kontrolaDna(r, i).equals("")) {
                // *** Duplicitne zmeny *** //
                JOptionPane.showMessageDialog(ZobrazRozpisTable, "Konflikt v " + (i + 1) + ". dni! Duplicitna zmena - " + kontrolaDna(r, i), "Duplicitný záznam!", JOptionPane.ERROR_MESSAGE);
//                System.out.println("Konflikt v " + (i+1) + ". dni! Duplicitna smena - " + kontrolaDna(r, i));
                return false;
            }
            // *** Kontrola nocna-denna na druhy den *** //
            if (!kontrolaSluzbyNextDay(r, i).equals("")) {
                JOptionPane.showMessageDialog(ZobrazRozpisTable, "Konflikt v " + (i + 1) + ". dni! Nezhoda v postupnosti nočná-denná zmena - " + kontrolaSluzbyNextDay(r, i), "Nočná-denná konflikt!", JOptionPane.ERROR_MESSAGE);
                return false;
            }
            // *** Kontrola typu zamestnanca na nocnu smenu *** //
            if (!kontrolaTypuZamestnanca(r, i).equals("")) {
                JOptionPane.showMessageDialog(ZobrazRozpisTable, "Konflikt v " + (i + 1) + ". dni! Nočnú zmenu môže mať len strážnik! Zmena - " + kontrolaTypuZamestnanca(r, i), "Zlý zvolený zamestnanec na nočnú zmenu!", JOptionPane.ERROR_MESSAGE);
                return false;
            }
        }
        return true;
    }
}
